function viewAirports(airports){
	clearAirportsAround();
	
	for(var i=0 ; i < airports.length ; i++){
		var airport = airports[i];
		var marker = insertMarker('images/airport.png',Number(airports[i].lat),Number(airports[i].lon));

		airportsAround.push([airports[i],marker]);
	}
	
	for(var i=0 ; i < airportsAround.length ; i++){
		google.maps.event.addListener(airportsAround[i][1], 'click', function(){
			var airport = getMarkerItem(this,'airport');
			generateHtmlPopupData(airport,'airport');
		});
	}
	
}

function viewAircrafts(json,aircraftId){
	if(json.flights){
		for(var i=0 ; i < json.flights.length ; i++){
			var aircraft = json.flights[i];
			if(aircraft.ownershipid != aircraftId) 
				animateFlightsAround(aircraft);
			}
	}
	
   // Flight Data Window
   for(var i=0 ; i < flightsAround.length ; i++){
		google.maps.event.addListener(flightsAround[i][1], 'click', function(){
			
			var aircraft = getMarkerItem(this,'flight');
			currentViewedItem = aircraft;
			

			generateHtmlPopupData(aircraft,'flight');
			
		});
	}
		
}



function animateFlightsAround(aircraft){
	var prevPosition;
	var prevLat;
	var prevLon;
	
	if(aircraft.hist == null){
		prevLat = aircraft.lat;
		prevLon = aircraft.lon;
	}
	else{
		var prevPosition = aircraft.hist.split(",");
		prevLat = Number(prevPosition[0]);
		prevLon = Number(prevPosition[1]); 
	}
	
	var lat = aircraft.lat;
	var lon = aircraft.lon;
	var diflat = Number(lat) - prevLat;
	var diflon = Number(lon) - prevLon;
	
	var unitDifLat = diflat / (radarUpdateTime / flightUpdateTime);
	var unitDifLon = diflon / (radarUpdateTime / flightUpdateTime);
	var rotation = rotateAircraft(null,diflon,diflat,false);
	
	var flightIndex = getFlightIndex(aircraft);
	
	if(flightIndex != -1){ // if exist
		flightsAround[flightIndex][1].setMap(null);
		window.clearInterval(flightsAround[flightIndex][2]);
		flightsAround.splice(flightIndex,1);
	}
	var marker = insertMarker('images/aircraft1/aircraft1_'+rotation+'.png',lat,lon);
	
	var flightThread = window.setInterval(function (a,b) {
		changeMarkerPosition(marker,lat+=unitDifLat,lon+=unitDifLon);
	},flightUpdateTime);
	flightsAround.push([aircraft,marker,flightThread]);
	
}

function useOwnershipInput(ownership){
	for(var i = 0; i < ownerships.length ; i++){
		if(ownership == ownerships[i].itemname){
			if(ownerships[i].type == 'aircraft'){
				playAircraft(ownerships[i],ownerships[i].username);
				changeUIOwnershipData('aircraft');
			}
		}
	}
}

function getFlightIndex(flight){
	for(var i = 0;i < flightsAround.length;i++){
		if(flightsAround[i][0].id == flight.id){
			return i;
		}
	}
	return -1;
}

function calculateDistance(lat1,lon1,lat2,lon2){
	 var R = 6371; // km 
	 var dLat = (lat2-lat1) * Math.PI / 180;
	 var dLon = (lon2-lon1) * Math.PI / 180;
	 var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(lat1 * Math.PI / 180 ) * Math.cos(lat2 * Math.PI / 180 ) * Math.sin(dLon/2) * Math.sin(dLon/2);
	 var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
	 var d = R * c;
	 
	 return d; // in km
}

function calculateSpeed(prevLat,prevLon,lat,lon){
	var rate = (1000 / flightUpdateTime);
	
	return parseInt(calculateDistance(prevLat,prevLon,lat,lon) * rate * 60 * 60);
	
}

function fillItemsBuy(itemsList){
	var listHtml='';
	for(var i = 0; i < itemsToBuy.length ; i++){
		var item = itemsToBuy[i];
		listHtml += '<li class="ui-widget-content" id="'+item.itemname+'"><IMG Src="images/'+item.itemname+'.png"/>&nbsp&nbsp<b>'+item.name+'</b> ('+item.price+')</li>';
	}
	itemsList.html(listHtml);
}

function changeUIOwnershipData(ownershipType){
	var listHtml='';
	if(ownershipType == 'aircraft'){
		listHtml += '<b>Speed : </b><label id="aircraftSpeedLabel"></label> km/h<br>';
		listHtml += '<b>Fuel : </b><label id="aircraftFuelLabel"></label><br>';
	}
	
	$("#ownershipData").html(listHtml);
	
}

function clearOwnershipsAround(){
	while(ownershipsAround.length != 0){
		ownershipsAround[ownershipsAround.length - 1][1].setMap(null);
		ownershipsAround.pop();
	}
}

function clearAirportsAround(){
	while(airportsAround.length != 0){
		airportsAround[airportsAround.length - 1][1].setMap(null); // remove marker
		airportsAround.pop();
	}
}

function setUIValue(componentId,value){
	$( "#"+componentId ).text(value);
}

function getMarkerItem(marker,itemType){
	var itemArray;
	
	if(itemType == 'airport') itemArray = airportsAround;
	else if(itemType == 'ownership') itemArray = ownershipsAround;
	else if(itemType == 'flight') itemArray = flightsAround;

	for(var i=0;i < itemArray.length ; i++){
		if(marker.__gm_id == itemArray[i][1].__gm_id) return itemArray[i][0];

	}
	return null;
	
}

function viewPopupData(title,htmlText,width,height,top,backgroundColor){
	$("#dataWindow").css( "opacity", 0.8 );
	$("#dataWindow").css( "width", width );
	$("#dataWindow").css( "height", height );
	$("#dataWindow").css( "left", ($("#map_canvas").width() - width)/2);
	$("#dataWindow").css( "top", top );
	$("#dataWindow").css( "background",backgroundColor);
	$("#dataWindow").html('<center><b>' + title + '</b></center><br>' + htmlText);
	
	var delay = window.setInterval(function (a,b) {
		$("#dataWindow").hide();
		currentViewedItem = null;
		window.clearInterval(delay);
	},15000);
	
	$("#dataWindow").show();
}

function viewIncomingMessage(title,htmlText,width,height,top,backgroundColor){
	$("#incomingMessageWindow").css( "opacity", 0.8 );
	$("#incomingMessageWindow").css( "width", width );
	$("#incomingMessageWindow").css( "height", height );
	$("#incomingMessageWindow").css( "left", ($("#map_canvas").width() - width)/2);
	$("#incomingMessageWindow").css( "top", top );
	$("#incomingMessageWindow").css( "background",backgroundColor);
	$("#incomingMessageWindow").html('<center><b>' + title + '</b></center><br>' + htmlText);
	
	var delay = window.setInterval(function (a,b) {
		$("#incomingMessageWindow").hide();
		currentViewedItem = null;
		window.clearInterval(delay);
	},5000);
	
	$("#incomingMessageWindow").show();
}


function generateHtmlPopupData(data,type){
	var htmlText='';
	
	if(type == 'airport'){
		htmlText = 	'<b>Airport Code :</b>  ' + data.airportcode + '<br>' +
					'<b>Latitude	 :</b>	' + data.lat + '<br>' +
					'<b>Longitude	 :</b>	' + data.lon + '<br>' + 
					'<b>Distance	 : <label id="distance"></label>km.<br>' +
					'<button id="landToAirportButton">Land here</button>';

		currentViewedItem = data;
		viewPopupData(data.airportname + ' Airport',htmlText,400,150,20,'#FECA40');
		
		
		// END FLIGHT
		
		$("#landToAirportButton").button().click(function(){
			if(Number($("#distance").text()) < 100){
				$.ajax({
				   type: "POST",
				   url: "/FlightGame/app/flight/end",
				   data:"id="+currentItem[0][0].id+"&airportcode="+data.airportcode,
				   dataType: "json",
				   success: function(json){
					   window.clearInterval(currentItem[0][1]);
					   window.clearInterval(currentItem[0][2]);
					   clearOwnershipsAround();
					   //clearAirportsAround();
					   aircraftMarker.setMap(null);
					   currentItem.pop();
					   difLat = 0;
					   difLon = 0;
					   aircraftDrive=false;
					   
					   ownerships = json.params.ownerships;
				   }
				 });
			}
		});
		
	}
	else if(type == 'flight'){
		htmlText = 	'<b>Owner    :</b>  ' + data.username + '<br>' +
					'<b>Latitude : </b><label id="aircraftLatitude"></label><br>' +
					'<b>Longitude: </b><label id="aircraftLongitude"></label><br>' + 
					'<b>Distance : </b><label id="distance"></label> KM.<br>' +
					'<b>Message  : </b><br><label id="message"></label><input value="" size="20" id="messageField"><br>';
		viewPopupData(data.aircraftname,htmlText,300,200,20,'#FECA40');

		$("#messageField").keypress(function(event) {
			if ( event.which == 13 ) { // enter
				$.ajax({
					   type: "POST",
					   url: "/FlightGame/app/flight/newmessage",
					   data:"sendid="+currentItem[0][0].id+"&receiveid="+data.ownershipid+"&isflightmsg=true"+"&message="+$("#messageField").val(),
					   success: function(json){
					   }
				});
			}
		});
	
	}
	else if(type == 'ownership'){
		htmlText = 	'<b>Owner 		: </b>' + data.username + '<br>' +
					'<b>Latitude	: </b>' + data.lat + '<br>' +
					'<b>Longitude	: </b>' + data.lon + '<br>' + 
					'<b>Distance	: <label id="distance"></label>km.<br>';
		if(data.type == 'gasstation'){
		htmlText += '<button id="buyFuelButton">Buy Fuel</button>';
		
		viewPopupData(data.type,htmlText,400,150,20,'#FECA40');
		$("#buyFuelButton").button().click(function(){
			$.ajax({
				   type: "POST",
				   url: "/FlightGame/app/flight/buyfuel",
				   data:"id="+currentItem[0][0].id+"&idstation="+data.id+"&quantity=100",
				   dataType: "json",
				   success: function(json){
					   setUIValue('aircraftFuelLabel',json.params.fuel);
					   setUIValue('userCredits',json.params.credits);

				   }
				 });
		});
		}
		currentViewedItem = data;
	}
	
	else if(type == 'message'){
		if(data[0].isflight == true){
			viewIncomingMessage('Message from ' + data[0].from,data[0].msg,400,100,100,'#FF0000');
		}
	}
	return htmlText;
}
